//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.kun.portal.webframe.controller;

import com.alibaba.fastjson.JSONObject;
import com.kun.framework.core.core.Configuration;
import com.kun.framework.core.util.DateUtils;
import com.kun.framework.crypto.cipher.DesCipher;
import com.kun.framework.web.web.vo.ValueLabelVo;
import com.kun.portal.webframe.exception.FwBaseException;
import com.kun.portal.webframe.po.FwTeamPo;
import com.kun.portal.webframe.po.FwUserPo;
import com.kun.portal.webframe.po.LoginLogPo;
import com.kun.portal.webframe.service.FwRoleService;
import com.kun.portal.webframe.service.FwTeamService;
import com.kun.portal.webframe.service.FwUserService;
import com.kun.portal.webframe.service.LoginLogService;
import com.kun.portal.webframe.util.FwBaseUtil;
import com.kun.portal.webframe.util.HeaderUtil;
import com.kun.portal.webframe.util.UserSessionUtil;
import com.kun.portal.webframe.vo.LoginConfigVo;
import com.kun.portal.webframe.vo.Teams;

import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import netscape.javascript.JSObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller


@RequestMapping({"/api/webframe"})
public class FwUserController {
    private static final Logger LOG = LoggerFactory.getLogger(FwUserController.class);
    @Autowired
    private FwUserService fwuserService;
    @Autowired
    private FwTeamService fwteamService;
    @Autowired
    private FwRoleService fwroleService;
    @Autowired
    private LoginLogService loginLogService;



    public FwUserController() {
    }
    @RequestMapping(
            value = {"/logout"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public void logout(HttpSession session ,HttpServletResponse response,HttpServletRequest request) {
            //session.invalidate();
        String s= (String) session.getAttribute("mvcPath");
        LoginConfigVo loginConfigVo = (LoginConfigVo) session.getAttribute("loginConfigVo");
        UserSessionUtil.clean(session);

        try {
            response.sendRedirect(s+loginConfigVo.getLoginRedirectUri());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping(
            value = {"/fwuser"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FwUserPo> findFwUser(@RequestParam(required = false) String key, Pageable pageable, HttpSession session) {
//        FwTeamPo fwTeam = null;
//        try{
//             fwTeam = UserSessionUtil.getCurrentUserTeam(session);
//        }catch (Exception e){
//
//        }
        return StringUtils.isEmpty(key)? this.fwuserService.findAll(pageable):this.fwuserService.findAll("%" + key + "%", pageable);
    }
    @RequestMapping(
            value = {"/fAllFwUser"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FwUserPo> findAllFwUser(HttpSession session) {
         return fwuserService.findAllUsers() ;
    }


    @RequestMapping(
            value = {"/loginLog"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map<String, Object> loginLog(HttpSession session) {
        FwUserPo fwUserPo = (FwUserPo) session.getAttribute("userInfo");
        return loginLogService.getLoginInfo(fwUserPo) ;
    }




    @RequestMapping(
            value = {"/fwuser/check"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public List<FwUserPo> findByFwUserUnique(@RequestBody Map<String, String> map, HttpSession session) {
        return this.fwuserService.findByFwUserUnique(map);
    }

    @RequestMapping(
            value = {"/fwuser/transferByRole/{roleId}"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map queryUserByRoleId(@PathVariable("roleId") String roleId, HttpSession session) {
        Map result = new HashMap();
        FwUserPo user = UserSessionUtil.getCurrentUser(session);
        List<FwUserPo> allcreated = this.fwuserService.findFwUserByCreator(user.getUserId());
        List<String> selected = this.fwuserService.findFwUserByRoleId(roleId);
        result.put("dataUsers", allcreated);
        result.put("myUsers", selected);
        return result;
    }

    @RequestMapping(
            value = {"/fwuser/transferByTeam/{teamId}"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map queryUserByTeamId(@PathVariable("teamId") String teamId, HttpSession session) {
        Map result = new HashMap();
        FwUserPo user = UserSessionUtil.getCurrentUser(session);
        List<FwUserPo> allcreated = this.fwuserService.findFwUserByCreator(user.getUserId());
        result.put("dataUsers", allcreated);
        return result;
    }

    @RequestMapping(
            value = {"/fwuser/updateFwRoleUserByRoleId"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public Map updateFwRoleUserByUserId(@RequestBody Map map, HttpSession session) {
        List<String> userIds = (List)map.get("userIds");
        String roleId = (String)map.get("roleId");
        this.fwuserService.updateFwRoleUserByUserId(userIds, roleId);
        return null;
    }

    @RequestMapping(
            value = {"/fwuser/updateFwTeamUserByTeamId"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public Map updateFwTeamUserByTeamId(@RequestBody Map map, HttpSession session) {
        List<Map<String,String>> users = (List) map.get("users");
        List<FwUserPo> fwUsers = new ArrayList<>();
        for (Map <String,String> ignored :users ){
            FwUserPo userPo =  new FwUserPo();
            userPo.setUserId(ignored.get("userId"));

            fwUsers.add(userPo);
        }
        String teamId = (String)map.get("teamId");
        this.fwteamService.updateFwTeamUserByTeamId(teamId,fwUsers.size()>0?fwUsers:null);
        return null;
    }

    @RequestMapping(
            value = {"/fwuser"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public ResponseEntity<FwUserPo> addFwUser(@RequestBody FwUserPo fwuser, HttpSession session) throws Exception {
        FwUserPo user = UserSessionUtil.getCurrentUser(session);
        fwuser.setCreator(user.getUserId());
        fwuser.setCreateTime(DateUtils.getNowDate());
        fwuser.setModifyTime(DateUtils.getNowDate());
        fwuser.setUserPwd(DesCipher.encrypt(fwuser.getNewPwd()));
//        FwTeamPo item;
//        if(fwuser.getTeams().size() == 0) {
//            item = FwBaseUtil.getCurTeam(session);
//            if(!Teams.SysTeam.name().equals(item.getTeamId()) && !"1".equals(item.getTeamLevel())) {
//                FwTeamPo team = UserSessionUtil.getCurrentUserTeam(session);
//                Set<FwTeamPo> teams = new HashSet();
//                teams.add(team);
//                fwuser.setTeams(teams);
//            }
//        } else {
//            Iterator var8 = fwuser.getTeams().iterator();
//
//            while(var8.hasNext()) {
//                item = (FwTeamPo)var8.next();
//                if(Teams.AllTeam.name().equals(item.getTeamId())) {
//                    fwuser.deleteTeam(item);
//                }
//            }
//        }

        FwUserPo metaFwUser = this.fwuserService.updateFwUser(fwuser);
        return new ResponseEntity(metaFwUser, HttpStatus.OK);
    }

    @RequestMapping(
            value = {"/fwuser"},
            method = {RequestMethod.PUT}
    )
    @ResponseBody
    public ResponseEntity<FwUserPo> updateFwUser(@RequestBody FwUserPo fwuser, HttpSession session) throws Exception {
        if(fwuser.getUserId() == null) {
            return this.addFwUser(fwuser, session);
        } else {
            FwUserPo oldUser = this.fwuserService.findOne(fwuser.getUserId());
            if(StringUtils.isNotEmpty(fwuser.getNewPwd())) {
                fwuser.setUserPwd(DesCipher.encrypt(fwuser.getNewPwd()));
            } else {
                fwuser.setUserPwd(oldUser.getUserPwd());
            }

            fwuser.setModifyTime(DateUtils.getNowDate());
//            FwTeamPo team = UserSessionUtil.getCurrentUserTeam(session);
//            Set<FwTeamPo> teams = new HashSet();
//            teams.add(team);
//            fwuser.setTeams(teams);
            FwUserPo metaFwUser = this.fwuserService.updateFwUser(fwuser);
            return new ResponseEntity(metaFwUser, HttpStatus.OK);
        }
    }

    @RequestMapping(
            value = {"/fwuser/{userId}"},
            method = {RequestMethod.DELETE}
    )
    @ResponseBody
    public ResponseEntity<Void> deleteFwUser(@PathVariable("userId") String userId) {
        this.fwuserService.deleteFwUser(userId);
        this.fwteamService.deleteFwTeamUserByUserId(userId);
        this.fwroleService.deleteFwRoleUserByUserId(userId);
        return ((BodyBuilder)ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("fwuser", userId))).build();
    }

    @RequestMapping(
            value = {"/fwuser/status"},
            method = {RequestMethod.PUT}
    )
    @ResponseBody
    public void updateFwUserStatus(@RequestBody Map<String, String> map) {
        this.fwuserService.updateFwUserStatus((String)map.get("userId"), (String)map.get("status"));
    }

    @RequestMapping(
            value = {"/fwuser/transfer/team"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public Map<String, List<FwUserPo>> getTeamTransferData(@RequestParam(required = false,defaultValue = "") String parentId, @RequestParam(required = false,defaultValue = "") String teamId, HttpSession session) {
        if(StringUtils.isEmpty(teamId) || "null".equals(teamId) || "CURRENT_TEAM".equals(teamId)) {
            teamId = FwBaseUtil.getTeamId(session);
        }

        if((StringUtils.isEmpty(parentId) || "null".equals(parentId)) && !"-1".equals(teamId)) {
            FwTeamPo team = this.fwteamService.findByTeamId(teamId);
            if(team == null) {
                throw new FwBaseException("团队不存在");
            }

            parentId = team.getParentCode();
        }

        Map<String, List<FwUserPo>> map = new HashMap();
        map.put("allUserList", this.fwuserService.findAllUser());
        map.put("selectUserList", this.fwuserService.findSelectUserByTeamId(teamId));
        return map;
    }

    @RequestMapping(
            value = {"/fwuser/transfer/role/{roleId}"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public Map<String, Object> getRoleTransferData(@PathVariable("roleId") String roleId) {
        Map<String, Object> map = new HashMap();
        map.put("allUserList", this.fwuserService.findAllUser());
        map.put("selectUserList", this.fwuserService.findSelectUserByRoleId(roleId));
        return map;
    }

    @RequestMapping(
            value = {"/fwuser/password"},
            method = {RequestMethod.PUT}
    )
    @ResponseBody
    public void editPassword(@RequestBody Map<String, String> map, HttpSession session) throws Exception {
        String userId = FwBaseUtil.getUserId(session);
        String pwd = DesCipher.encrypt((String)map.get("pwd"));
        String newPwd = DesCipher.encrypt((String)map.get("newPwd"));
        FwUserPo oldUser = this.fwuserService.findOne(userId);
        String oldPassword = oldUser.getPassword();
        if(pwd.equals(oldPassword)) {
            oldUser.setUserPwd(newPwd);
            this.fwuserService.updateFwUser(oldUser);
        } else {
            throw new FwBaseException("当前密码错误");
        }
    }

    @RequestMapping(
            value = {"/encryptPwd"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public Map<String, Object> encryptUserPwd(@RequestParam String password, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap();
        if(this.validatePwd(password)) {
            resultMap.put("success", Boolean.valueOf(true));
            resultMap.put("msg", DesCipher.encrypt(password));
        } else {
            resultMap.put("success", Boolean.valueOf(false));
            resultMap.put("msg", Configuration.getInstance().getProperty("com.kun.framework.web.controllers.UserController.passwordInfo"));
        }

        return resultMap;
    }

    private boolean validatePwd(String password) {
        return password.matches(Configuration.getInstance().getProperty("com.kun.framework.web.controllers.UserController.passwordReg"));
    }
}
